package com.isljj.web_chat2.utils;

import com.isljj.web_chat2.model.User;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.Map;



@Component
@Slf4j
public class JWTUtils {
//    有效时间 1h
    private final static long Expiration_Time  = 120*60*1000;

    private final static String secretString = "ww6FBiJ6/IugHuuw4qBzA/kvlr3/KOFLvxnCB5vFGyA=";
    private final static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
//    生成令牌
    public String genToken(Map<String ,Object> claims){

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+Expiration_Time)).
                signWith(key)
                .compact();
    }
//    解析令牌
     public Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;


        try {
            claims = build.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            log.info("token  已经过期");
            return null;
        }
        return claims;
    }

    public User getUserByToken(String token) {
        Claims claims = parseToken(token);
        if(claims==null){
            return null;
        }
        User user = new User();
        user.setUserId((Integer) claims.get("userId"));
        user.setUserName((String) claims.get("userName"));
        return user;
    }
//    校验令牌

}
